package com.shuaige.leaning.shiro.controller;

import com.shuaige.leaning.shiro.bean.ResponseBean;
import com.shuaige.leaning.shiro.bean.UserBean;
import com.shuaige.leaning.shiro.service.UserService;
import com.shuaige.leaning.shiro.util.JWTUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

@RestController
@Slf4j
public class WebController {

    private UserService userService;

    @Autowired
    public void setService(UserService userService) {
        this.userService = userService;
    }

    /**
     * http://localhost:8080/doLogin?username=javaboy&password=123
     */
    @PostMapping("/doLogin")
    public ResponseBean doLogin(@RequestParam("username") String username,
                                @RequestParam("password") String password) {
        UserBean userBean = userService.getUser(username);
        if (userBean.getPassword().equals(password)) {
            return new ResponseBean(200, "Login success", JWTUtil.sign(username, password));
        } else {
            throw new UnauthorizedException();
        }
    }

    @GetMapping("/login")
    public ResponseBean login() {
        return new ResponseBean(200, "login", "");
    }

    @GetMapping("/index")
    public ResponseBean index() {
        return new ResponseBean(200, "index", "");
    }

    /**
     * 登录后可访问
     */
    @GetMapping("/require_auth")
    @RequiresAuthentication
    public ResponseBean requireAuth() {
        return new ResponseBean(200, "You are authenticated", "");
    }

    /**
     * 包含admin角色可访问
     */
    @GetMapping("/require_role")
    @RequiresRoles("admin")
    public ResponseBean requireRole() {
        return new ResponseBean(200, "You are visiting require_role", "");
    }

    /**
     * 包含view、edit可访问
     */
    @GetMapping("/require_permission")
    @RequiresPermissions(logical = Logical.AND, value = {"view", "edit"})
    public ResponseBean requirePermission() {
        return new ResponseBean(200, "You are visiting permission require edit,view", "");
    }

    @RequestMapping(path = "/401")
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public ResponseBean unauthorized() {
        return new ResponseBean(401, "Unauthorized", "");
    }

}